package com.car.slave.im.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

public class IMHeartbeatTool {
	
	public interface OffLineCallback {
		void offLine();
	}
	
	private final int interval = 5000;
	private final byte[] buffer = new byte[6];
	private Timer mTimer;
	
	private long updateTime;
	
	private OffLineCallback callback;
	
	public IMHeartbeatTool(OffLineCallback callback) {
		super();
		this.callback = callback;
	}

	public void readBuffer(InputStream is) throws IOException {
		// 防止分包
		for (int i = 0; i < buffer.length; i++) {
			int b = is.read();
			buffer[i] = (byte)b;
		}
//		int len = is.read(buffer);
		// 更新心跳包接受的时间
		updateTime = System.currentTimeMillis();
	}
	
	public byte[] getHeadBuffer() {
		return buffer;
	}
	
	/**
	 * 是否是心跳包.
	 * @return
	 */
	public boolean isHeartbeat() {
		if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0) {
			return true;
		}
		return false;
	}
	
	public void startListener() {
//		updateTime = System.currentTimeMillis();
//		mTimer = new Timer();
//		mTimer.schedule(task, 0, interval);
	}
	
	public void cancelListener() {
//		mTimer.cancel();
	}
	
	final TimerTask task = new TimerTask() {
		@Override
		public void run() {
			System.out.println("time  " + (System.currentTimeMillis() - updateTime));
			if (System.currentTimeMillis() - updateTime > interval * 4) {
				callback.offLine();
			}
		}
	};
}
